package com.erp.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.Utils.DateFormat;
import com.erp.Utils.ResponseModel;
import com.erp.aopLog.Log;
import com.erp.entity.Demand;
import com.erp.entity.Project;
import com.erp.enums.moduleName;
import com.erp.enums.operationType;
import com.erp.enums.statusCode;
import com.erp.service.DemandService;
import com.erp.service.ProjectService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 项目管理表 前端控制器
 * </p>
 *
 * @author  张彬 
 * @since 2021-10-14
 */
@Controller
@RequestMapping("/project")
public class ProjectController {
    @Resource
    ProjectService projectService;
    @Resource
    DemandService demandService;

    @RequestMapping(value = "listView",method = RequestMethod.GET)
    @PreAuthorize("hasAnyAuthority('project:list')")
    public ModelAndView listView(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("system/project/project_list");
        return mav;
    }

    @RequestMapping(value = "/getListData",method = RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('project:list')")
    public Map<String,Object> getListData(@RequestParam(value = "page") int page,
                                          @RequestParam(value = "limit") int limit,
                                          @RequestParam(value = "projectName",required = false) String projectName,
                                          @RequestParam(value = "start",required = false) String start,
                                          @RequestParam(value = "end",required = false) String end){
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(projectName)){
            wrapper.like("project_name",projectName);
        }
        if (StrUtil.isNotEmpty(start) && StrUtil.isNotEmpty(end)){
            // 时间偏移一天
            Date date = DateUtil.parse(end,"yyyy-MM-dd");
            Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 1);
            String formatDate = DateUtil.formatDate(newDate);
            wrapper.ge("create_time",start).le("create_time",formatDate);
        }
        wrapper.eq("status",statusCode.Default.getValue()).orderByDesc("create_time");
        IPage<Project> userPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        if ((StrUtil.isNotEmpty(start) && StrUtil.isNotEmpty(end)) || StrUtil.isNotEmpty(projectName)){
            userPage = projectService.page(userPage, wrapper);
        }else{
            userPage = projectService.page(userPage, wrapper);
        }
        List<Project> projectList = userPage.getRecords();//获取数据，这里面还有当前页码数还有总数据参数
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",userPage.getTotal());
        map.put("data",projectList);


        Log.insert(moduleName.project.getMsg(),"查看项目列表", operationType.list.getValue());
        return map;
    }

    @RequestMapping(value = "editView",method = RequestMethod.GET)
    @PreAuthorize("hasAnyAuthority('project:edit')")
    public ModelAndView editView(@RequestParam int id){
        Project project = projectService.getById(id);
        ModelAndView mav = new ModelAndView();
        mav.addObject("project",project);
        mav.setViewName("system/project/editView");
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @PreAuthorize("hasAnyAuthority('project:edit')")
    public ResponseModel edit(@RequestBody JSONObject data){
        String projectName = data.getStr("projectName");
        String projectInfo = data.getStr("projectInfo");
        Project project = new Project();
        project.setId(Convert.toInt(data.get("projectId")));
        project.setProjectName(projectName);
        if (StrUtil.isNotEmpty(projectInfo)){
            project.setProjectInfo(projectInfo);
        }
        boolean status = projectService.updateById(project);
        if (status){
            Log.insert(moduleName.project.getMsg(),"id为"+data.get("projectId")+"项目名称已被修改", operationType.edit.getValue());
            return ResponseModel.success("修改成功");
        }else{
            return ResponseModel.fail("修改失败");
        }

    }
    @PreAuthorize("hasAnyAuthority('project:add')")
    @RequestMapping(value = "addView",method = RequestMethod.GET)
    public ModelAndView addView(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("system/project/addView");
        return mav;
    }
    @PreAuthorize("hasAnyAuthority('project:add')")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel add(@RequestBody JSONObject data){
        String projectName = data.getStr("projectName");
        String projectInfo = data.getStr("projectInfo");
        if (StrUtil.isEmpty(projectName)){
            return ResponseModel.fail("项目名不允许为空");
        }
        Project dbProject = projectService.getOne(new QueryWrapper<Project>().eq("project_name",projectName));
        if (dbProject != null){
            return ResponseModel.fail("此项目名已存在,请重新创建");
        }
        Project project = new Project();
        project.setProjectName(projectName);
        project.setProjectInfo(projectInfo);
        project.setCreateTime(DateFormat.getTime());
        project.setStatus(statusCode.Default.getValue());
        projectService.save(project);
        Log.insert(moduleName.project.getMsg(),"新增了一条"+projectName+"的项目信息", operationType.add.getValue());
        return ResponseModel.success("增加成功");
    }
    //删除
    @PreAuthorize("hasAnyAuthority('project:del')")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel del(@RequestBody Project data){
//        boolean status = projectService.removeById((int)data.get("projectId"));
        //做逻辑删除
        data.setStatus(statusCode.Delete.getValue());
        boolean status = projectService.updateById(data);
        // 逻辑删除项目下的所有需求
        delDemand(data.getProjectName());
        if (status){
            Log.insert(moduleName.project.getMsg(),"删除了一条"+data.getProjectName()+"的项目信息", operationType.del.getValue());
            return ResponseModel.success("删除成功");
        }else{
            return ResponseModel.fail("删除失败");
        }
    }
    // 批量删除
    @PreAuthorize("hasAnyAuthority('project:del')")
    @RequestMapping(value = "/batch/delete",method = RequestMethod.POST)
    @ResponseBody
//    public ResponseModel batchDel(@RequestBody  List<Integer> idList){
//        boolean status = projectService.removeByIds(idList);
    public ResponseModel batchDel(@RequestBody  List<Project> projectList){
        List<Object> list = new ArrayList<>();
        for (Project project:projectList){
            project.setStatus(statusCode.Delete.getValue());
            delDemand(project.getProjectName());
            //记录日志
            list.add(project.getProjectName());
        }
        boolean status = projectService.updateBatchById(projectList);
        if (status){
            Log.insert(moduleName.project.getMsg(),"删除了"+Convert.toStr(list)+"多条项目信息", operationType.del.getValue());
            return ResponseModel.success("删除成功");
        }else{
            return ResponseModel.fail("删除失败");
        }
    }

    /*
    逻辑删除项目下的需求公用函数
     */
    public void delDemand(String projectName){
        // 逻辑删除项目下的所有需求
        UpdateWrapper<Demand> projectUpdateWrapper = new UpdateWrapper<>();
        projectUpdateWrapper.eq("projectName",projectName).set("del_status",statusCode.Delete.getValue());
        demandService.update(null,projectUpdateWrapper);

    }

}
